const User = require('../models/User');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const UserModel = require('../models/User');

const authService = {
  // 用户注册
  async register(userData) {
    const { username, email, password } = userData;
    
    // 检查邮箱是否已被注册
    const existingUser = await UserModel.findByEmail(email);
    if (existingUser) {
      throw new Error('该邮箱已被注册');
    }
    
    // 创建新用户
    const userId = await UserModel.create({ username, email, password });
    return userId;
  },

  // 用户登录
  async login(credentials) {
    const { email, password } = credentials;
    
    // 查找用户
    const user = await UserModel.findByEmail(email);
    if (!user) {
      throw new Error('用户不存在');
    }
    
    // 验证密码
    const isPasswordValid = await UserModel.comparePassword(password, user.password);
    if (!isPasswordValid) {
      throw new Error('密码错误');
    }
    
    // 生成JWT令牌
    const token = jwt.sign(
      { id: user.id, email: user.email },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES_IN }
    );
    
    return { token, user: { id: user.id, username: user.username, email: user.email } };
  },

  // 验证JWT令牌
  async verifyToken(token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      return decoded;
    } catch (error) {
      throw new Error('无效的令牌');
    }
  },

  // 获取当前用户信息
  async getCurrentUser(userId) {
    const user = await UserModel.findById(userId);
    if (!user) {
      throw new Error('用户不存在');
    }
    
    // 返回不包含密码的用户信息
    return { id: user.id, username: user.username, email: user.email, created_at: user.created_at };
  },

  // 更新用户信息
  async updateUser(userId, userData) {
    const { username, email } = userData;
    
    // 检查邮箱是否已被其他用户使用
    const existingUser = await UserModel.findByEmail(email);
    if (existingUser && existingUser.id !== userId) {
      throw new Error('该邮箱已被其他用户使用');
    }
    
    await UserModel.update(userId, { username, email });
    return { success: true };
  },

  // 修改密码
  async changePassword(userId, currentPassword, newPassword) {
    const user = await UserModel.findById(userId);
    
    // 验证当前密码
    const isPasswordValid = await UserModel.comparePassword(currentPassword, user.password);
    if (!isPasswordValid) {
      throw new Error('当前密码错误');
    }
    
    await UserModel.changePassword(userId, newPassword);
    return { success: true };
  }
};

module.exports = authService;